#!/bin/sh

## a script to restore files backuped by svn/cvs etc.
## %_loc: _home_/bin %

## $Id: mrst 16 2007-10-06 08:32:03Z dhg $

REVISION=`grep "[$]Id" $0 | cut -d ' ' -f 4`
CMD_NAME=`grep "[$]Id" $0 | cut -d ' ' -f 3`

if [ ! -z "${1}" ]; then
	echo ''
	echo "${CMD_NAME} revision: ${REVISION}"
	echo "usage: execute '${CMD_NAME}' without any arguments."
	echo ''
	exit 0
fi

CURPATH=.
DIFF=`which diff`
DIFF_QUIET="`which diff` -q"
DIFF_OPTS="-anu"
PAGER=${PAGER:-more}

for file in ${CURPATH}/*; do

	if [ -f ${file} ]; then

		orig_path=`grep "[%]_loc" ${file} | cut -d ' ' -f 3`
		real_name=`grep "[$]Id" ${file} | cut -d ' ' -f 3`

		[ ! -z ${real_name} ] && \
		real_name=`echo ${real_name} | sed "s|^dot\.|\.|g"`

		[ ! -z ${orig_path} ] && \
		orig_path=`echo ${orig_path} | \
					sed "s|^_home_|"$HOME"|g" | \
					sed "s|^_root_||g" | \
					sed "s|^_local_|\.|g"`

	else
		orig_path=/dev/null
	fi

	if [ ! -d  ${orig_path} ]; then
		continue
	else

		filename=`basename ${file}`

		[ ! -z "${real_name}" ] && filename=$real_name

		orig_file="${orig_path}/${filename}"

		if [ -f ${orig_file} ]; then

				result=`${DIFF_QUIET} ${orig_file} ${file}`

				if [ ! -z "${result}" ]; then

				${DIFF} ${DIFF_OPTS} ${orig_file} ${file} | ${PAGER}

				echo ''
				echo "===> [i] to install ${file} as ${orig_file}"
				echo "===> [r] ${orig_file} will remain untouched."
				echo ''
				echo -e '\a'
				echo -n '===> your choice? [leave it for later]:'

				read _key

				case "${_key}" in
					i)
						echo "---> installing ${file} as ${orig_file}"
						cp -p ${file} ${orig_file}
						echo ''
						;;
					r)
						echo "===> ${orig_file} will remain untouched."
						echo ''
						;;
					*)
						echo "===> ${file} remains awaiting your later revision.:)"
						echo ''
						;;
				esac
			fi
		fi

	orig_path=
	filename=
	orig_file=

	fi

done

exit 0
